package com.atstudy.filter;

import com.atstudy.entites.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/2/2 10:52
 * @copyright: 博为峰
 */
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    private List<String> list = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        String uri = servletContext.getInitParameter("unInterceptUri");
        String[] strings = uri.split(",");
        list = Arrays.asList(strings);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();//    /web03_war_exploded/login.jsp
        uri = uri.substring(uri.lastIndexOf("/"));//  /login.jsp

        if (list.contains(uri)) {
            filterChain.doFilter(request, response);
        } else {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            if (user != null) {
                filterChain.doFilter(request, response);
            } else {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
